package com.qianfeng.smartdevices.service.impl;

import com.qianfeng.smartdevices.cache.RoleCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.RoleChangeEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.exceptions.DeleteErrorException;
import com.qianfeng.smartdevices.exceptions.UpdateErrorException;
import com.qianfeng.smartdevices.mapper.RoleMapper;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.pojo.Role;
import com.qianfeng.smartdevices.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    private RoleMapper roleMapper;
    private RoleCache roleCache;
    private ApplicationContext context;
    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Override
    public List<Role> findRoleByUserId(Long uid) {
        return roleMapper.findRoleByUserId(uid);
    }

    @Override
    public List<Role> findAllRole() {
//        return roleMapper.findAllRole();
        return roleCache.getAllData();
    }

    @Override
    public void addRole(Role role) {
        if (role.isNull(CheckStatus.ADD)){
            throw new AddErrorException("添加数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        roleMapper.addRole(role);
        context.publishEvent(new RoleChangeEvent());
    }

    @Override
    public void updateRole(Role role) {
        if (role.isNull(CheckStatus.UPDATE)){
            throw new UpdateErrorException("更新的数据不能为空",ResultCode.DATA_NOT_ALLOW_NUL);
        }
        roleMapper.updateRole(role);
        context.publishEvent(new RoleChangeEvent());
    }

    @Override
    public void deleteRole(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new DeleteErrorException("删除需要传递ids",ResultCode.DATA_NOT_ALLOW_NUL);
        }
        roleMapper.deleteRole(Arrays.asList(ids));
        context.publishEvent(new RoleChangeEvent());
    }


}
